package com.gqh.weather.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;

/**
 * @description MyBatis-Plus配置类
 * @author AI
 * @date 2025-09-21
 */
@Configuration
public class MybatisPlusConfig {

    @Autowired
    private DataSource dataSource;

    /**
     * MyBatis-Plus 拦截器配置
     * 注意：分页插件在 MyBatis-Plus 3.5.x 版本中已经简化配置
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 自动识别数据库类型
        DbType dbType = getDbType();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(dbType)); // 如果配置多个插件, 切记分页最后添加

        return interceptor;
    }

    /**
     * 根据数据源自动识别数据库类型
     */
    private DbType getDbType() {
        try {
            String url = dataSource.getConnection().getMetaData().getURL();
            if (url.contains(":mysql:")) {
                return DbType.MYSQL;
            } else if (url.contains(":dm:")) {
                return DbType.DM;
            }
            // 默认返回 MySQL
            return DbType.MYSQL;
        } catch (Exception e) {
            // 异常时默认返回 MySQL
            return DbType.MYSQL;
        }
    }

}